package net.bithappens.hnqe.impl.rest.handler;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Set;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import net.bithappens.hnqe.graph.EntryValue;
import net.bithappens.hnqe.graph.GraphElement;
import net.bithappens.hnqe.graph.GraphRelationMember;
import net.bithappens.hnqe.impl.rest.provider.CalendarJsonAddapter;
import net.bithappens.hnqe.impl.rest.provider.EntryValueJsonAddapter;
import net.bithappens.hnqe.impl.rest.provider.GraphElementJsonAddapter;
import net.bithappens.hnqe.impl.rest.provider.GraphRelationMemberJsonAddapter;
import net.bithappens.hnqe.query.Instance;
import net.bithappens.hnqe.query.QueryTree;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


@Path("/hnqe/query")
public class RestQuery extends RootResource{

	private Logger log = Logger.getLogger(this.getClass());
	
	@Context 
	private UriInfo uriInfo;
	
	
	@GET
	@Path("/{instanceId}")
	@Produces({"application/json"})
	public Response queryGraph(
			@PathParam("instanceId") String instanceId,
			@QueryParam("minSize") @DefaultValue("0") String minSize,
			@QueryParam("query") String query) throws Exception{
		
		if(query == null || query.isEmpty()){
			return Response.noContent().build();
		}
		
		QueryXMLParser queryParser = new QueryXMLParser();
		
		queryParser.parse(query);
		
		QueryTree queryTreeObject = queryParser.parse(query);
		
		Set<Instance> instances = hnqe.getQueryInterface().queryGraph(instanceId, Integer.valueOf(minSize), queryTreeObject);
		
		if(instances == null || instances.size() == 0){
			return Response.noContent().build();
		} else {
			Gson gson = new GsonBuilder()
				.registerTypeAdapter(GraphRelationMember.class, new GraphRelationMemberJsonAddapter())
				.registerTypeAdapter(GraphElement.class, new GraphElementJsonAddapter())
				.registerTypeAdapter(Calendar.class, new CalendarJsonAddapter())
				.registerTypeAdapter(GregorianCalendar.class, new CalendarJsonAddapter())
				.create();
        	;
			return Response.ok(gson.toJson(instances), "application/json").build();	
		}
	}
}
